package com.matrix.order.interfaces.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyV3Result;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.matrix.order.application.OrderAppService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 有点甜
 * @since 2025/7/28
 */
@Slf4j
@RestController
@RequestMapping("/api/order/payment")
@RequiredArgsConstructor
public class PaymentNotifyController {

    private final WxPayService wxPayService;
    private final OrderAppService orderAppService;

    @PostMapping("/notify")
    public String handlePaymentNotify(@RequestBody String notifyData) {
        log.info("接收到微信支付回调通知: {}", notifyData);
        try {
            WxPayOrderNotifyV3Result result = wxPayService.parseOrderNotifyV3Result(notifyData, null);

            WxPayOrderNotifyV3Result.Amount amount = result.getResult().getAmount();
            String tradeState = result.getResult().getTradeState();
            String paymentNo = result.getResult().getOutTradeNo();

            if ("SUCCESS".equals(tradeState)) {
                log.info("支付单 {} 支付成功,金额: {} 分", paymentNo, amount.getPayerTotal());
                orderAppService.handlePaymentSuccess(paymentNo, amount.getPayerTotal());
            } else {
                log.warn("支付单 {} 支付状态异常: {}", paymentNo, tradeState);
            }

            return WxPayNotifyResponse.success("处理成功");

        } catch (WxPayException e) {
            log.error("微信支付回调处理失败", e);
            return WxPayNotifyResponse.fail(e.getMessage());
        } catch (Exception e) {
            log.error("处理支付回调时发生未知异常", e);
            return WxPayNotifyResponse.fail("服务器内部错误");
        }
    }
}
